import { Message } from '../types/chat';
// 基础URL，可以根据环境配置
const BASE_URL = 'http://192.168.1.222:8866';

// --- MOCK IMPLEMENTATION START ---
const MOCK_ENABLED = true;

// Mock database
let mockChatList = [
    { chat_id: 'mock-chat-1', icon: '', role_id: 1, model_id: 1, title: '之前保存的会话1', edit: false, removing: false },
    { chat_id: 'mock-chat-2', icon: '', role_id: 1, model_id: 1, title: '如何用 Go 实现 http client', edit: false, removing: false },
];

export let mockChatHistories: { [key: string]: Message[] } = {
    'mock-chat-1': [
        { type: "prompt", id: 'p1', icon: '', content: '你好' },
        { type: "reply", id: 'r1', icon: '', content: '你好，我是模拟AI，有什么可以帮您？' },
    ],
    'mock-chat-2': [
        { type: "prompt", id: 'p2', icon: '', content: '如何用 Go 实现 http client' },
        { type: "reply", id: 'r2', icon: '', content: '在 Go 中，你可以使用 net/http 包来实现 HTTP client。这是一个简单的模拟例子...' },
    ]
};

const mockApiHandlers: Record<string, Record<string, (params?: any) => any>> = {
    '/api/model/list': {
        GET: () => ({ data: [{ id: 1, name: 'Mock-Model-R1', value: 'mock-model-r1', power: 1 }, { id: 2, name: 'Deepseek-R1 (Mock)', value: 'deepseek-r1', power: 1 }] }),
    },
    '/api/app/list/user': {
        GET: () => ({ data: [{ id: 1, name: '智能对话助手', icon: '', key: 'gpt', model_id: 0, hello_msg: '您好，我是您的模拟AI助手，有什么可以帮助您的吗？' }] }),
    },
    // '/api/chat/list': {
    //     GET: () => ({ data: mockChatList }),
    // },
    '/api/chat/history': {
        GET: (params: { chat_id: string }) => ({ data: mockChatHistories[params.chat_id as keyof typeof mockChatHistories] || [] }),
    },
    '/api/chat/remove': {
        GET: (params: { chat_id: string }) => {
            mockChatList = mockChatList.filter(chat => chat.chat_id !== params.chat_id);
            delete mockChatHistories[params.chat_id as keyof typeof mockChatHistories];
            return { data: null };
        }
    },
    '/api/chat/update': {
        POST: (body: { chat_id: string, title: string }) => {
            mockChatList = mockChatList.map(chat => {
                if (chat.chat_id === body.chat_id) {
                    return { ...chat, title: body.title, edit: false };
                }
                return { ...chat, edit: false };
            });
            return { data: null };
        }
    },
    '/api/chat/clear': {
      GET: () => {
        mockChatList = [];
        mockChatHistories = {} as typeof mockChatHistories;
        return { data: null };
      }
    }
};

const handleMockRequest = async (method: string, url: string, paramsOrData?: unknown): Promise<ApiResponse<unknown> | null> => {
    if (!MOCK_ENABLED) {
        return null;
    }
    
    const urlPath = url.split('?')[0];
    const handler = mockApiHandlers[urlPath]?.[method.toUpperCase()];

    if (handler) {
        console.log(`[MOCK] ${method}: ${url}`, paramsOrData);
        let params = paramsOrData;
        if (method.toUpperCase() === 'GET' && url.includes('?')) {
            const queryParams = new URLSearchParams(url.split('?')[1]);
            params = Object.fromEntries(queryParams.entries());
        }
        const result = handler(params);
        return Promise.resolve({ code: 0, message: 'mocked success', data: result.data });
    }

    console.warn(`[MOCK] No mock handler for ${method}: ${url}`);
    return Promise.resolve({ code: 0, message: 'mocked success', data: {} });
};
// --- MOCK IMPLEMENTATION END ---

// HTTP请求选项接口
interface RequestOptions {
  method: string;
  headers: Record<string, string>;
  body?: string | FormData;
}

// 响应数据接口
interface ApiResponse<T = unknown> {
  code: number;
  message: string;
  data: T;
}

// 获取存储的token
const getToken = (): string | null => {
  if (typeof window !== 'undefined') {
    return localStorage.getItem('token');
  }
  return null;
};

// 创建请求选项
const createRequestOptions = (method: string, data?: unknown, contentType = 'application/json'): RequestOptions => {
  const options: RequestOptions = {
    method,
    headers: {
      'Accept': 'application/json',
    },
  };

  const token = getToken();
  if (token) {
    options.headers['Authorization'] = `Bearer ${token}`;
  }

  if (data) {
    if (data instanceof FormData) {
      options.body = data;
    } else {
      options.headers['Content-Type'] = contentType;
      options.body = JSON.stringify(data);
    }
  }

  return options;
};

// 处理响应
const handleResponse = async <T>(response: Response): Promise<ApiResponse<T>> => {
  if (!response.ok) {
    const errorData = await response.json().catch(() => ({}));
    throw new Error(errorData.message || `请求失败: ${response.status}`);
  }

  const contentType = response.headers.get('content-type');
  if (contentType && contentType.includes('application/json')) {
    return await response.json();
  }

  throw new Error('响应格式不是JSON');
};

// GET请求
export const httpGet = async <T = unknown>(url: string, params?: Record<string, unknown>): Promise<ApiResponse<T>> => {
  const mockResponse = await handleMockRequest('GET', url, params);
  if (mockResponse) return mockResponse as ApiResponse<T>;

  let queryUrl = url;

  if (params) {
    const queryParams = new URLSearchParams();
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== null) {
        queryParams.append(key, String(value));
      }
    });
    
    const queryString = queryParams.toString();
    if (queryString) {
      queryUrl += (url.includes('?') ? '&' : '?') + queryString;
    }
  }

  const options = createRequestOptions('GET');
  const response = await fetch(`${BASE_URL}${queryUrl}`, options);
  return handleResponse<T>(response);
};

// POST请求
export const httpPost = async <T = unknown>(url: string, data?: unknown): Promise<ApiResponse<T>> => {
  const mockResponse = await handleMockRequest('POST', url, data);
  if (mockResponse) return mockResponse as ApiResponse<T>;

  const options = createRequestOptions('POST', data);
  const response = await fetch(`${BASE_URL}${url}`, options);
  return handleResponse<T>(response);
};

// PUT请求
export const httpPut = async <T = unknown>(url: string, data?: unknown): Promise<ApiResponse<T>> => {
  const mockResponse = await handleMockRequest('PUT', url, data);
  if (mockResponse) return mockResponse as ApiResponse<T>;

  const options = createRequestOptions('PUT', data);
  const response = await fetch(`${BASE_URL}${url}`, options);
  return handleResponse<T>(response);
};

// DELETE请求
export const httpDelete = async <T = unknown>(url: string): Promise<ApiResponse<T>> => {
  const mockResponse = await handleMockRequest('DELETE', url);
  if (mockResponse) return mockResponse as ApiResponse<T>;

  const options = createRequestOptions('DELETE');
  const response = await fetch(`${BASE_URL}${url}`, options);
  return handleResponse<T>(response);
};

// 上传文件
export const httpUpload = async <T>(url: string, file: File, fieldName = 'file'): Promise<ApiResponse<T>> => {
  const mockResponse = await handleMockRequest('POST', `${url}?upload=true`, { file, fieldName });
  if (mockResponse) return mockResponse as unknown as Promise<ApiResponse<T>>;

  const formData = new FormData();
  formData.append(fieldName, file);
  
  const options = createRequestOptions('POST', formData);
  delete options.headers['Content-Type']; // 让浏览器自动设置正确的Content-Type
  
  const response = await fetch(`${BASE_URL}${url}`, options);
  return handleResponse<T>(response);
}; 